/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.find.memories.util;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Build;

/** Junk drawer of utility methods. */
public final class PhotoUtil {
	static final Charset US_ASCII = Charset.forName("US-ASCII");
	static final Charset UTF_8 = Charset.forName("UTF-8");
	private static final int HONEYCOMB = 11;

	private PhotoUtil() {
	}

	static String readFully(Reader reader) throws IOException {
		try {
			StringWriter writer = new StringWriter();
			char[] buffer = new char[1024];
			int count;
			while ((count = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, count);
			}
			return writer.toString();
		} finally {
			reader.close();
		}
	}

	/**
	 * Deletes the contents of {@code dir}. Throws an IOException if any file
	 * could not be deleted, or if {@code dir} is not a readable directory.
	 */
	static void deleteContents(File dir) throws IOException {
		File[] files = dir.listFiles();
		if (files == null) {
			throw new IOException("not a readable directory: " + dir);
		}
		for (File file : files) {
			if (file.isDirectory()) {
				deleteContents(file);
			}
			if (!file.delete()) {
				throw new IOException("failed to delete file: " + file);
			}
		}
	}

	static void closeQuietly(/* Auto */Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (RuntimeException rethrown) {
				throw rethrown;
			} catch (Exception ignored) {
			}
		}
	}

    public static boolean hasFroyo() {
        // Can use static final constants like FROYO, declared in later versions
        // of the OS since they are inlined at compile time. This is guaranteed behavior.
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= HONEYCOMB;
    }
    
    /**
     * url에서 resizing 높이값이 있다면 0으로 변경
     * @param path
     * @param fix_width
     * @return String
     */
    public static String preFixPhotoPath(String path, int fix_width) {
    	String fix = new String();
    	if (path != null && !path.equals("")) {
    		int width_index = path.indexOf("?w=");
			int height_index = path.indexOf("&h=");
			
			if (!(width_index < 0 || height_index < 0))  {
				String tempWidth = path.substring(width_index+3, width_index+7);
				String tempHeight = path.substring(height_index+3, height_index+7);
				tempWidth = getNumeral(tempWidth);
				tempHeight = getNumeral(tempHeight);
				int width = Integer.parseInt(tempWidth);
				int height = Integer.parseInt(tempHeight);
				if (height != 0) {
					String split[] = path.split("\\&h=");
					if (split != null && split.length >= 2) {
						if (split[1] != null && !split[1].equals("")) {
							fix = split[0]+"&h="+split[1].replaceFirst(tempHeight, "0");
						}
					}
				}
				if (width > fix_width) {
					String split[] = fix.split("\\?w=");
					if (split != null && split.length >= 2) {
						if (split[1] != null && !split[1].equals("")) {
							fix = split[0]+"?w="+split[1].replaceFirst(tempWidth, String.valueOf(fix_width));
						}
					}
				}
			} else {
				fix = path;
			}
    	}
    	return fix;
    }
    
    /**
     * 숫자만 걸러내 주는 기능
     * @param str
     * @return String
     */
    private static String getNumeral(String str) {
		String numeral = new String();
		
		if (null != str) {
			String patternStr = "\\d";
			Pattern pattern = Pattern.compile(patternStr);
			Matcher matcher = pattern.matcher(str);
			
			while (matcher.find()) {
				numeral += matcher.group(0);
			}
		} else {
			numeral = null;
		}
		
		return numeral;
	}
    
    /**
     * 년월일 표시 형식을 변경해 준다.
     * @param date
     * @return String
     */
    public static String changeDateDisplay(String date) {
		String change = null;
		if (date != null && !date.equals("")) {
			if (date.length() >= 8) {
				change = date.replaceAll("\\-", "");
				change = change.replaceAll("\\.", "");
				String year = change.substring(0, 4);
				String month = change.substring(4, 6);
				String day = change.substring(6, 8);
				change = year+"."+month+"."+day;
			}
			else {
				change = date;
			}
		}
		return change;
	}
    
    /**
     * 서버에서 newline(\n)을 |||로 내려주기 때문에 \n으로 변경해준다.
     * @param memo
     * @return String
     */
    public static String getNewLineString(String memo) {
		String fix = "";
		if (memo != null && !memo.isEmpty()) {
			fix = memo.replaceAll("\\|\\|\\|", "\n");
		}
		return fix;
	}
    
    /**
     * 현재 메모영역에 엤는 newline(\n)을 |||로 변경해준다.
     * @param memo
     * @return String
     */
    public static String getPreFixNewLineString(String memo) {
		String fix = "";
		if (memo != null && !memo.isEmpty()) {
			fix = memo.replaceAll("\n", "\\|\\|\\|");
		}
		return fix;
	}
}
